package com.jy.framework.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jy.framework.sys.dao.SysAreaDao;
import com.jy.framework.sys.dto.AreaTreeDTO;
import com.jy.framework.sys.entity.SysAreaEntity;
import com.jy.framework.sys.service.SysAreaService;
import com.jy.framework.sys.service.TreeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;


@Service("sysAreaService")
public class SysAreaServiceImpl extends ServiceImpl<SysAreaDao, SysAreaEntity> implements SysAreaService {

    /**
     * 地区
     */
    private final String REGION_KEY = SysAreaEntity.class.getName();

    /**
     * 换成KEY·
     */
    private final String CACHE_KEY = "AreaKey";
    @Autowired
    private TreeService treeService;
    @Override
    public boolean save(SysAreaEntity entity) {
        super.save(entity);
        treeService.updateParentIds(this,entity);
        return true;
    }
    @Override
    public boolean updateById(SysAreaEntity entity) {
        treeService.updateParentIds(this, entity);
        return super.updateById(entity);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        for (Serializable id :
                idList) {
            treeService.delByParentId(this, id);
        }
        return true;
    }

    @Override
    public List<AreaTreeDTO> getAreaTree(String pId) {
        return baseMapper.getAreaTree(pId);
    }

    @Override
    public List<SysAreaEntity> getAllListCache() throws Exception {

        List<SysAreaEntity> list;
        list = this.baseMapper.selectList(new QueryWrapper<>());

        return list;
    }

    @Override
    public SysAreaEntity getObj(String code, String name) throws Exception {

        List<SysAreaEntity> list = getAllListCache();
        SysAreaEntity areaObj = null;
        for (SysAreaEntity area : list) {
            if (code != null && code.equals(area.getId().toString())) {
                areaObj = area;
                break;
            }

            if (!StringUtils.isEmpty(name) && name.equals(area.getName())) {
                areaObj = area;
                break;
            }
        }
        return areaObj;
    }

    @Override
    public void fillParentIds() {
        treeService.fillParentIds(this);
    }

}
